package com.example.sonny.dutest;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.cengalabs.flatui.FlatUI;
import com.example.sonny.Constraint;
import com.example.sonny.dutest.interfaces.BaseActivityI;
import com.example.sonny.util.AsyncHttpClientUtil;
import com.example.sonny.util.VolleyImageUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class MyProfileActivity extends BaseActivity implements BaseActivityI{

    private static final int REQUEST_IMAGE = 2048;
    private EditText et_name;
    private EditText et_email;
    private EditText et_image;
    private EditText et_created_at;
    private ImageView iv_profile;

    private String name;
    private String email;
    private String image;
    private String created_at;

    private Button btn_back;
    private Button btn_done;

    private String action;
    private Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_profile);
        preInit();
        initView();
        initListener();
        initData();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_my_profile, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if(id == android.R.id.home) {
            // app icon in action bar clicked; goto parent activity.
            this.finish();
            return true;
        }
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void preInit() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        actionBar.setBackgroundDrawable(FlatUI.getActionBarDrawable(this, FlatUI.GRASS, false));
    }

    @Override
    public void initView() {

        et_email = (EditText)findViewById(R.id.et_my_college);
        et_image = (EditText)findViewById(R.id.et_my_faculty);
        et_created_at = (EditText)findViewById(R.id.et_my_major);
        et_name = (EditText)findViewById(R.id.et_my_nickname);

        iv_profile = (ImageView)findViewById(R.id.profile_my_avater_img);
        btn_back = (Button)findViewById(R.id.profile_btn_back);
        btn_done = (Button)findViewById(R.id.profile_btn_done);

        iv_profile.setClickable(true);


    }

    @Override
    public void initListener() {

        btn_back.setOnClickListener(this);
        btn_done.setOnClickListener(this);
        iv_profile.setOnClickListener(this);
    }

    @Override
    public void initData() {

        AsyncHttpClient client = AsyncHttpClientUtil.getInstence();

        action  = "api/profile";//TODO set action URL
        client.get(Constraint.API_URL + action, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                toast("信息获取成功");
                //TODO  set specific items
                try {
                    name = response.getString("name");
                    email = response.getString("email");
                    image = response.getString("image");
                    created_at = response.getString("created_at");

                    et_name.setText(name);
                    et_email.setText(email);
                    et_image.setText(image);
                    et_created_at.setText(created_at);


                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                toast("信息获取失败");
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.profile_btn_back:
                Log.i(LogTag,"返回界面");
                finish();
                break;
            case R.id.profile_btn_done:
                if(checkState()){
                    changeProfileJob();
                }else{
                    finish();
                }
                break;
            case R.id.profile_my_avater_img:
                selectJob();

        }

    }
    private void selectJob() {
        Intent intent = new Intent(getApplicationContext(), MultiImageSelectorActivity.class);

// 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);

// 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);

// 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);

        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_IMAGE){
            if(resultCode == RESULT_OK){
                // 获取返回的图片列表
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                // 处理你自己的逻辑 ....
                iv_profile.setImageURI(Uri.parse(path.get(0)));
                //Do some compress work
                bitmap = VolleyImageUtils.getScaledBitmap(path.get(0), 256, 256);
                //VolleyImageUtils.compress(path.get(0),path.get(0),48,48,50);
                //TODO make detail correct
            }
        }
    }

    private boolean checkState(){

       if(et_email.getText().toString().equalsIgnoreCase(email) &&
               et_image.getText().toString().equalsIgnoreCase(image)&&
               et_created_at.getText().toString().equalsIgnoreCase(created_at)&&
               et_name.getText().toString().equalsIgnoreCase(name)){
           return false;
       }
        return true;

    }



    private void changeProfileJob() {
        AsyncHttpClient client = AsyncHttpClientUtil.getInstence();

        action  = "api/profile";//TODO set specific action
        RequestParams requestParams = new RequestParams();
        requestParams.add("name",name);
        requestParams.add("email",email);
        requestParams.add("image",image);
        client.post(Constraint.API_URL+action,requestParams,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    String result=response.getString("result").toString();
                    toast("修改"+result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                toast("修改失败");
            }
        });

    }
}
